<template>
	<el-dialog v-model="visible" width="40%" :z-index="9" @close="cancelHandle">
		<template #header>
			<div class="custom-header">{{ isUpdateFlag ? '通知新增' : '通知编辑' }}</div>
		</template>

		<div class="">
			<el-form ref="queryForm" label-width="120px" class="mt20" :model="queryParams" :rules="rules">
				<el-form-item label="通知发布名称" prop="noticePublishName">
					<el-input v-model="queryParams.noticePublishName" placeholder="通知发布名称" clearable :disabled="isChakanFlag" />
				</el-form-item>
				<el-form-item label="通知发布日期" prop="noticePublishDate">
					<el-date-picker
						v-model="queryParams.noticePublishDate"
						style="width: 100%"
						type="date"
						:disabled="isChakanFlag"
						value-format="YYYY-MM-DD HH:mm:ss"
						format="YYYY-MM-DD"
						placeholder="通知发布日期"
					/>
				</el-form-item>

				<el-form-item label="" prop="noticePublishFileId">
					<el-upload
						ref="uploadRef"
						:action="uploadApi"
						:headers="uploadHeaders"
						:data="uploadData"
						accept=".pdf"
						:limit="1"
						:file-list="uploadShowList"
						:disabled="isChakanFlag"
						style="width: 90%"
						:on-exceed="handleExceed"
						:on-preview="handleUploadFilePreview"
						:on-success="handleUploadFileSuccess"
						:on-error="handleUploadFileError"
						:on-remove="handleUploadfileRemove"
					>
						<el-button v-if="!isChakanFlag" type="primary">上传附件(pdf)</el-button>
						<!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
					</el-upload>
				</el-form-item>
			</el-form>
			<div class="dialog-footer">
				<el-button v-if="!isChakanFlag" type="primary" @click="sumbitHandle(queryForm)">提交</el-button>
				<el-button @click="cancelHandle">关闭</el-button>
			</div>
		</div>
	</el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'

import type { FormInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

import { govNoticePublishAddApi, govNoticePublishDetailApi, govNoticePublishEditApi } from '@/api/government/index'
import { filePreviewByName } from '@/api/sys/upload'
import { UploadFile } from '@/interface/declare'

import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()

const queryForm = ref(null)
const visible = ref()
const isUpdateFlag = ref(false)
const isChakanFlag = ref(false)
const queryParams = ref({
	noticePublishName: '',
	noticePublishDate: '',
	noticePublishFileId: ''
})
const emit = defineEmits(['refreshDataList'])
// const emit = defineEmits<{ (event: 'update:visible', value: boolean): void; (event: 'chananniu', value: ''): void }>()

const rules = reactive({
	noticePublishName: [{ required: true, message: '请输入通知发布名称', trigger: 'blur' }],
	noticePublishDate: [{ required: true, message: '请选择通知发布日期', trigger: ['change', 'blur'] }],
	noticePublishFileId: [{ required: true, message: '请选择附件文件', trigger: ['change', 'blur'] }]
})

const init = (isUpdate: Boolean, row: any, isChakan: Boolean) => {
	isUpdateFlag.value = isUpdate
	isChakanFlag.value = isChakan
	if (!isUpdate) {
		detailMethods(row.id)
	}
	visible.value = true
}
const detailMethods = async (id: String | Number) => {
	// var params = {
	//     id: id
	// }
	await govNoticePublishDetailApi(id).then(res => {
		queryParams.value['id'] = res.data.id
		queryParams.value['noticePublishName'] = res.data.noticePublishName
		queryParams.value['noticePublishDate'] = res.data.noticePublishDate
		queryParams.value['noticePublishFileId'] = res.data.noticePublishFileId
		fileShow(res.data)
	})
}
const fileShow = (row: any) => {
	var file = {}
	if (row.noticePublishFileId) {
		Object.assign(file, row.attachment)
		file['name'] = row.attachment['fileName'] ? row.attachment['fileName'] : '附件'
		file['systemFileName'] = row.noticePublishFileId
		file['id'] = row.noticePublishFileId

		uploadShowList.value.push(file)
		uploadList.value.push(file)
		console.log(uploadList.value, '文件需要', queryParams.value)
	}
}
const resetForm = () => {
	const data = {
		noticePublishName: '',
		noticePublishDate: '',
		noticePublishFileId: ''
	}
	queryParams.value = data
}
const cancelHandle = () => {
	queryForm.value?.resetFields() // 表单验证关闭
	resetForm()
	visible.value = false
	isChakanFlag.value = false
	isUpdateFlag.value = false
	// 文件清空
	uploadList.value = []
	uploadShowList.value = []
	emit('refreshDataList')
}
const sumbitHandle = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (uploadList.value.length > 0) {
				queryParams.value.noticePublishFileId = uploadList.value[0]['id']
			}
			// console.log(queryParams.value)
			if (isUpdateFlag.value) {
				submitAddRecord()
			} else {
				submitEditRecord()
			}
		} else {
			console.log('提交错误', fields)
		}
	})
}
// 新增
const submitAddRecord = async () => {
	await govNoticePublishAddApi(queryParams.value).then(res => {
		ElMessage.success({
			message: '操作成功',
			duration: 500
		})
		cancelHandle()
	})
}

const submitEditRecord = async () => {
	var params = JSON.parse(JSON.stringify(queryParams.value))
	delete params.id
	await govNoticePublishEditApi(queryParams.value['id'], params).then(res => {
		ElMessage.success({
			message: '操作成功',
			duration: 500
		})
		cancelHandle()
	})
}
// 附件上传
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'other',
	remark: '附件'
}
const uploadRef = ref()
const uploadList = ref<UploadFile[]>([])
const uploadShowList = ref<UploadRawFile[]>([])
const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}

const handleUploadFilePreview = (ruploadFile: any) => {
	// console.log(ruploadFile)
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const handleUploadFileSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList.value = []
		uploadList.value.push(res.data)
		queryParams.value.noticePublishFileId = res.data.id
	} else {
		handleUploadFileError(res, uploadFile)
	}
}

const handleUploadfileRemove = (file: UploadRawFile) => {
	uploadList.value = []
	queryParams.value.noticePublishFileId = ''
}

const handleUploadFileError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowList.value = uploadShowList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}
defineExpose({
	init
})
</script>

<style lang="scss" scoped>
.boardBox {
	display: flex;
	align-items: center;
	flex-direction: column;
	flex-wrap: wrap;
	justify-content: space-around;
	overflow-y: scroll;
	height: 100%;

	&::-webkit-scrollbar {
		display: none;
	}

	-ms-overflow-style: none;
	scrollbar-width: none;

	.tishi {
		font-size: 14px;
		color: #999;
		background-color: #f3f8fb;
		padding: 5px 10px;
		border-radius: 6px;
	}
}
</style>
